<?php
/**
 * 跨域中转
 * 伪静态
 *
location / {
	if (!-e $request_filename){
		rewrite  ^(.*)$  /index.php?s=$1  last;   break;
	}
}
 */
if(!checkreferer()){
    http_response_code(404);
    echo json_encode(['error' => 'Not Found']);
    exit;
}
// 禁用所有可能的缓冲
ini_set('output_buffering', 'off');
ini_set('zlib.output_compression', false);
header('X-Accel-Buffering: no');
// 获取请求方法和路径
$method = $_SERVER['REQUEST_METHOD'];
// 构建Ollama API的URL
$ollamaUrl = trim( parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH),'/');
// 检查是否是API请求
if (strpos($ollamaUrl, '/api/')==-1) {
    http_response_code(404);
    echo json_encode(['error' => 'Not Found']);
    exit;
}
// 处理输入数据
$inputData = file_get_contents('php://input');
$headers = getallheaders();
// 准备请求头
$requestHeaders = [
    'Content-Type: application/json',
    'Accept: text/event-stream'
];
// 保留必要的原始头
foreach ($headers as $key => $value) {
    if (in_array(strtolower($key), ['authorization', 'content-type', 'accept'])) {
        $requestHeaders[] = "$key: $value";
    }
}
// 检查是否是流式请求
$isStreaming = isset($_GET['stream']) && $_GET['stream'] === 'true';
// 初始化cURL
$ch = curl_init($ollamaUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POSTFIELDS, $inputData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, !$isStreaming);
curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
if ($isStreaming) {
    // 流式响应处理
    header('Content-Type: text/plain; charset=utf-8');
    header('Cache-Control: no-cache');
    header('Connection: keep-alive');
    header('X-Accel-Buffering: no');
    ob_end_clean(); // 关闭输出缓冲
    ob_implicit_flush(true);
    ob_start();
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($curl, $data) {
        echo $data;
        ob_flush();
        flush();
        return strlen($data);
    });
    curl_exec($ch);
} else {
    // 普通响应处理
    $response = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    http_response_code($status);
    echo $response;
}
// 关闭cURL
curl_close($ch);
function checkreferer(){
    $url = $_SERVER['HTTP_REFERER'];
    if(empty($url))return false;
    $domains=['localhost','tool.bitefu.net'];
    $host = parse_url($url, PHP_URL_HOST);
    return in_array($host,$domains);
}
?>